package com.ruoyi.project.system.apply.controller;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.apply.domain.CoinApply;
import com.ruoyi.project.system.apply.dto.CoinApplyDto;
import com.ruoyi.project.system.apply.service.ICoinApplyService;
import com.ruoyi.project.system.coinrecord.domain.HondaCoinRecord;
import com.ruoyi.project.system.coinrecord.dto.HondaCoinRecordDto;
import com.ruoyi.project.system.coinrecord.enums.CoinIncome;
import com.ruoyi.project.system.coinrecord.service.IHondaCoinRecordService;
import com.ruoyi.project.system.coupon.usercoupon.service.IUserCouponService;
import com.ruoyi.project.system.dealer.service.IDealerService;
import com.ruoyi.project.system.giftbag.giftbagtinfo.service.IGiftBagInfoService;
import com.ruoyi.project.system.member.domain.Member;
import com.ruoyi.project.system.member.service.IMemberService;
import com.ruoyi.project.system.membercar.domain.MemberCar;
import com.ruoyi.project.system.membercar.dto.MemberCarDto;
import com.ruoyi.project.system.membercar.service.IMemberCarService;
import com.ruoyi.project.system.user.service.IUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * 积分增加申请Controller
 * 
 * @author f_baisi
 * @date 2020-08-14
 */
@Controller
@RequestMapping("/system/apply")
public class CoinApplyController extends BaseController
{
    private String prefix = "system/apply";

    @Autowired
    private ICoinApplyService coinApplyService;

    @Autowired
    private IHondaCoinRecordService hondaCoinRecordService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private IMemberCarService memberCarService;
    @Autowired
    private IGiftBagInfoService giftBagInfoService;
    @Autowired
    private IUserCouponService userCouponService;

    @Autowired
    private IDealerService dealerService;

    @Autowired
    private IUserService userService;

    @RequiresPermissions("system:apply:view")
    @GetMapping()
    public String apply(ModelMap map)
    {
        map.put("post",this.userService.findPostIdsByUid(getUserId()));
        return prefix + "/apply";
    }

    /**
     * 查询积分增加申请列表
     */
    @RequiresPermissions("system:apply:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(CoinApply coinApply)
    {
        startPage();
        List<CoinApplyDto> list = coinApplyService.selectCoinApplyList(coinApply);
        for(CoinApplyDto mem :list){
            mem.setMemberCar(this.memberCarService.findByUid(mem.getMemberId()));
        }
        return getDataTable(list);
    }

    /**
     * 导出积分增加申请列表
     */
    @RequiresPermissions("system:apply:export")
    @Log(title = "积分增加申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(CoinApply coinApply)
    {
        List<CoinApplyDto> list = coinApplyService.selectCoinApplyList(coinApply);
        for(CoinApplyDto coinApplyDto:list){
            coinApplyDto.setTypeName(CoinIncome.getByValue(coinApplyDto.getType()).getName());
            MemberCar memberCar = memberCarService.findByUid(coinApplyDto.getMemberId());
            if (memberCar!=null) {
                coinApplyDto.setName(memberCar.getName());
                coinApplyDto.setLicensePlate(memberCar.getLicensePlate());
                coinApplyDto.setFrameNo(memberCar.getFrameNo());
            }

//            if (memberCar==null) {
//                coinApplyDto.setLicensePlate("-");
//            } else {
//                coinApplyDto.setFrameNo(memberCar.getFrameNo());
//            }

        }
        ExcelUtil<CoinApplyDto> util = new ExcelUtil<CoinApplyDto>(CoinApplyDto.class);
        return util.exportExcel(list, "apply");
    }

    /**
     * 新增积分增加申请
     */
    @GetMapping("/add")
    public String add(ModelMap map)
    {
        map.put("userList",this.memberService.findAllHasCar());
        map.put("dealerList",this.dealerService.findByUserPost(getUserId()));
        return prefix + "/add";
    }

    /**
     * 新增保存积分增加申请
     */
    @RequiresPermissions("system:apply:add")
    @Log(title = "积分增加申请", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public String addSave(CoinApply coinApply)
    {
        coinApply.setCreated(DateUtils.getNowDate());
        coinApply.setCreator(getUserId());
        coinApply.setStatus(0);
        coinApplyService.insertCoinApply(coinApply);
        return "redirect:/"+prefix + "/add";
    }

    /**
     * 修改积分增加申请
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        CoinApply coinApply = coinApplyService.selectCoinApplyById(id);
        mmap.put("coinApply", coinApply);
        return prefix + "/edit";
    }

    /**
     * 修改保存积分增加申请
     */
    @RequiresPermissions("system:apply:edit")
    @Log(title = "积分增加申请", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(CoinApply coinApply)
    {
        return toAjax(coinApplyService.updateCoinApply(coinApply));
    }

    /**
     * 删除积分增加申请
     */
    @RequiresPermissions("system:apply:remove")
    @Log(title = "积分增加申请", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(coinApplyService.deleteCoinApplyByIds(ids));
    }



    @PostMapping("/agree/{id}")
    @ResponseBody
    @Transactional
    public AjaxResult agree(@PathVariable String id){
        CoinApply coinApply = this.coinApplyService.selectCoinApplyById(id);
        if(coinApply==null){
            return AjaxResult.error();
        }
        CoinApply update = new CoinApply();
        update.setId(id);
        update.setStatus(1);
        update.setUpdateTime(DateUtils.getNowDate());
        update.setUpdateUser(getUserId());
        this.coinApplyService.updateCoinApply(update);

        //生成积分记录
        HondaCoinRecord hondaCoinRecord = new HondaCoinRecord();
        hondaCoinRecord.setNum(coinApply.getTotal());
        hondaCoinRecord.setCreated(DateUtils.getNowDate());
        hondaCoinRecord.setStatus(1);
        hondaCoinRecord.setType(0);
        hondaCoinRecord.setMemberId(coinApply.getMemberId());
        hondaCoinRecord.setGetType(coinApply.getType());
        //用户积分增加
        Member member = this.memberService.selectMemberById(coinApply.getMemberId());
        if(coinApply.getType()!=11){
            this.hondaCoinRecordService.insertHondaCoinRecord(hondaCoinRecord);

            Member updateMember = new Member();
            updateMember.setId(coinApply.getMemberId());
            updateMember.setCoin(member.getCoin().add(coinApply.getTotal()));
            updateMember.setSumCoin(member.getSumCoin().add(coinApply.getTotal()));
            this.memberService.updateCoinMember(updateMember,member);

        }

        //判断是否存在推荐人
        if(member.getIntroUser()!=null){
            MemberCarDto byUid = this.memberCarService.findByUid(member.getIntroUser());
            //判断推荐人是否绑定车辆
            if(byUid!=null){
                HondaCoinRecord hondaCoin;
                Member introUser;
                Member updateIntroUser;
                //根据类型判断给推荐人增加积分
                switch (coinApply.getType()){
                    case 11:
                        introUser= this.memberService.selectMemberById(member.getIntroUser());
                        HondaCoinRecord select = new HondaCoinRecord();
                        select.setGetType(3);
                        select.setMemberId(introUser.getId());
                        select.setType(0);
                        select.setStatus(1);
                        List<HondaCoinRecordDto> hondaCoinRecordDtos = this.hondaCoinRecordService.selectHondaCoinRecordList(select);

                        //生成积分记录
                        hondaCoin= new HondaCoinRecord();
                        hondaCoin.setCreated(DateUtils.getNowDate());
                        hondaCoin.setStatus(1);
                        hondaCoin.setType(0);
                        hondaCoin.setMemberId(introUser.getId());
                        hondaCoin.setGetType(3);
                        switch (hondaCoinRecordDtos.size()){
                            case 0:
                                hondaCoin.setNum(new BigDecimal(10000));
                                break;
                            case 1:
                                hondaCoin.setNum(new BigDecimal(16000));
                                break;
                            case 2:
                                hondaCoin.setNum(new BigDecimal(20000));
                                break;
                            default:
                                hondaCoin.setNum(new BigDecimal(20000));
                        }
                        this.hondaCoinRecordService.insertHondaCoinRecord(hondaCoin);
                        updateIntroUser = new Member();
                        updateIntroUser.setCoin(introUser.getCoin().add(hondaCoin.getNum()));
                        updateIntroUser.setSumCoin(introUser.getSumCoin().add(hondaCoin.getNum()));
                        updateIntroUser.setId(introUser.getId());
                        this.memberService.updateCoinMember(updateIntroUser,introUser);
                        break;
                }
            }
        }

        return AjaxResult.success();
    }

    @PostMapping("/refuse/{id}")
    @ResponseBody
    public AjaxResult refuse(@PathVariable String id){
        CoinApply carUsedAppointment = this.coinApplyService.selectCoinApplyById(id);
        if(carUsedAppointment==null){
            return AjaxResult.error();
        }
        CoinApply update = new CoinApply();
        update.setId(id);
        update.setStatus(2);
        update.setUpdateTime(DateUtils.getNowDate());
        update.setUpdateUser(getUserId());
        this.coinApplyService.updateCoinApply(update);

        return AjaxResult.success();
    }

}
